package com.atguigu.datastream.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink01_Batch_WordCount
 * Package: com.atguigu.day01
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/6 16:53
 * @Version 1.0
 */
public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        //1 .获取Flink批处理环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.读取文件
        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        //3.将数据读取过来按照空格切分为一个个单词
        FlatMapOperator<String, String> wordData = dataSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(word);
                }
            }
        });

        //4.将单词组成Tuple2元组  第二个元素为1，为了将每个单词标记上数量，方便后面计算，其次将单词设置为第一个元素，可以方便后面按照单词聚合
        MapOperator<String, Tuple2<String, Long>> wordToOne = wordData.map(new MapFunction<String, Tuple2<String, Long>>() {
            /**
             *
             * @param s
             * @return  将单词返回为（word,1）
             * @throws Exception
             */
            @Override
            public Tuple2<String, Long> map(String s) throws Exception {
                return new Tuple2<>(s, 1L);
            }
        });

        //5.按照单词分组，将相同的单词聚合到一块(spark：ReducBykey功能(1.将相同的key聚合 2.将聚合后的数据做计算))
        UnsortedGrouping<Tuple2<String, Long>> groupBy = wordToOne.groupBy(0);

        //6.将聚合后的value数据做sum累加操作
        AggregateOperator<Tuple2<String, Long>> result = groupBy.sum(1);

        //7. 打印
        result.print();


    }
}
